#include <cstdlib>
#include <string>
#include <pthread.h>
#include <string>
#include <cstring>

#include "../include/contest_interface.h"
#include "../include/Iterator.h"
#include "../include/Mutex.h"
#include "../include/IndexSchema.h"
#include "../include/Index.h"
#include "../include/tx.h"
#include "../include/util.h"
#include "../include/IteratorLink.h"
#include "../include/AutoCommitTx.h"

ErrorCode AutoCommitInsertRecord(Index *idx, Record *record) {
    try {
        ErrorCode ret;
        Transaction *tx_a;
        ret = BeginTransaction(&tx_a);
        if (ret == kOk) {
            if (tx_a->Tx_index() == NULL)
                tx_a->Tx_set_index(idx);
            if (!(tx_a->Tx_isHandled()))
                idx->HandleTransaction(&tx_a);
            tx_a->Tx_set_autoCommit();
            ret = idx->getSchema()->get_QuadTree()->insert(record);
        }
        AutoCommitEndTransaction(&tx_a);

        return ret;
    } catch (std::bad_alloc &e) {
        return kErrorOutOfMemory;
    } catch (ErrorCode &e) {
        return e;
    } catch (...) {
        return kErrorGenericFailure;
    }
    return kOk;

}

ErrorCode AutoCommitEndTransaction(Transaction **tx) {
    try {
        delete (*tx);
        (*tx) = NULL;
    } catch (...) {
        throw kErrorGenericFailure;
    }
    return kOk;
}

